package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端认证拦截器
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(StrUtil.isEmpty( token )){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        try {
            Claims claims = tokenService.parseToken(token);
            log.info("claims: {}", claims);
            if(claims==null){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new BaseException("认证失败");
            }

            Long userId = MapUtil.get(claims, "userId", Long.class);
            log.info("userId: {}", userId);
            if(userId == null){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new BaseException("认证失败");
            }

            //设置用户信息到ThreadLocal
            UserThreadLocal.set(userId);
            return true;

        }catch (Exception e){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("认证失败");
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
